#coding=utf-8
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from apps.userModel.models import User, Game, Travel, Record

from wechatpy import parse_message, create_reply
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException
from wechatpy.replies import BaseReply

import wx_event, auto_reply
from message_lib import reply_msg
from paginator import get_page

'''
    todo:
        1. 分页
        2. 
'''

list_args = {
    "ticket_session": "ticket_session__contains",
    "start_city":"start_city__contains",
}


def _get_list(request):

    ls = Record.objects.filter()
    args = {}
    for ak in list_args.keys():
        if request.GET.get(ak, None):
            try:
                args[str(list_args.get(ak))] = str(request.GET.get(ak, None))
            except UnicodeEncodeError:
                args[str(list_args.get(ak))] = request.GET.get(ak, None)
    ls = ls.filter(**args)
    return ls

@csrf_exempt
def test(request):
    return render(request, 'index.html')

@csrf_exempt
def record_showall(request):

    # ls = _get_list(request)
    # record = get_page(ls,request)
	return redirect("https://worldcup.dmpb.com.cn/front/dist/index.html")
    # return render(request, 'index.html', {'recordlist':record})

@csrf_exempt
def record_insertview(request):
    #判断用户是否已经填过表
    openId = request.session["openid"]
    try:
        Record.objects.filter(wxid=openId).get()
    except Record.DoesNotExist:
        return render(request, 'travel_insert.html')
    else:
        record = Record.objects.all();
        return render(request, 'recordinfo.html', {'recordlist':record,'message':'信息提交成功!'})

@csrf_exempt
def record_insert(request):

    wxname = request.POST.get("wxname")
    # wxid = request.POST.get("wxid")
    wxid = request.session["openid"]
    gender = request.POST.get("gender")
    if gender == "男":
        gender = 1
    else:
        gender = 2
    phone = request.POST.get("phone")
    start_city = request.POST.get("start_city")
    start_date = request.POST.get("start_date")
    end_date = request.POST.get("end_date")
    accompanyno = request.POST.get("accompanyno")
    #ticket_type = request.POST.get("ticket_type")
    transfer_type = request.POST.getlist("transfer_type")
    ticket_session = request.POST.getlist("ticket_session")
    ticket_arena = request.POST.getlist("ticket_arena")
    ticket_team = request.POST.getlist("ticket_team")
    ticket_team_count = request.POST.getlist("ticket_team_count")
    remark = request.POST.get("remark")

    #validation need to do
    if wxname == "":
        return render(request, 'record_editview.html', {'message':'昵称不能为空！'})
    # if start_city == "":
    #     return render(request, 'record_editview.html', {'message':'出发城市不能为空！'})
    if phone == "":
        return render(request, 'record_editview.html', {'message':'手机号不能为空'})
    
    record = Record()
    record.wxname = wxname
    record.wxid = wxid
    record.gender = int(gender)
    record.phone = phone
    record.accompanyno = accompanyno
    record.start_city = start_city
    record.start_date = start_date
    record.end_date = end_date
    record.ticket_type = ''
    record.transfer_type = ';'.join(transfer_type)
    record.ticket_session = ';'.join(ticket_session)
    record.ticket_arena = ';'.join(ticket_arena)
    record.ticket_team = ';'.join(ticket_team)
    record.ticket_team_count = ';'.join(ticket_team_count)
    record.remark = remark
    record.save()
    user = User()
    user.wxname = wxname
    user.wxid = wxid
    user.gender = int(gender)
    user.phone = phone
    user.hashit = '1'
    user.save()
    record = Record.objects.all()
    return render(request, 'recordinfo.html', {'recordlist':record,'message':'信息提交成功!'})

@csrf_exempt
def record_update(request):
    '''
        记录的更新
    '''
    pass


@csrf_exempt
def search_by_city(request):
    '''
        按城市搜索
    '''
    city = request.GET.get('city')
    record = Record.objects.filter(start_city__contains=city)
    return render(request, 'userinfo.html', {'userinfo':record, 'tab':'tab_city'})

@csrf_exempt
def search_by_session(request):
    '''
        按场次搜索
    '''
    session = request.GET.get('ticket_session')
    record = Record.objects.filter(ticket_session__contains=session)
    return render(request, 'userinfo.html', {'userinfo':record, 'tab':'tab_session'})


'''
    以下暂时不动
'''

@csrf_exempt
def user_info(request):
    userinfo = User.objects.all()
    return render(request, 'userinfo.html', {'userinfo':userinfo})

@csrf_exempt
def user_edit(request):
    userinfo = User.objects.all()
    return render(request, 'index_bak.html', {'userinfo':userinfo})

@csrf_exempt
def user_submit(request):
    userinfo = User.objects.all()
    return render(request, 'usersubmit.html', {'userinfo':userinfo})

@csrf_exempt
def travel_insert(request):
    userlist = User.objects.all()
    return render(request, 'index_bak.html', {'userlist':userlist})


TOKEN='dmpb'

@csrf_exempt
def weixin(request):
    '''
        从公众号过来的请求
    '''
    if request.method == 'GET':
        signature = request.GET.get('signature', '')
        timestamp = request.GET.get('timestamp', '')
        nonce = request.GET.get('nonce', '')
        echo_str = request.GET.get('echostr', '')
        try:
            check_signature(TOKEN, signature, timestamp, nonce)
        except InvalidSignatureException:
            echo_str = 'token check error'
        response = HttpResponse(echo_str, content_type="text/plain")
        return response
    else:
        reply = None
        msg = parse_message(request.body)
        if msg.type != 'event':
            reply = auto_reply.apply(msg)
        else:
            reply = wx_event.apply(msg)
        if not reply or not isinstance(reply, BaseReply):
            reply = create_reply(reply_msg['reply_format_warning'])
        response = HttpResponse(reply.render(), content_type="application/xml")
        return response

#球衣需求调查
@csrf_exempt
def JerseysDemand(request):

    return render(request, 'jerseys_demand.html')
